package cn.yh.hospitalappointmentsystemdemo.interceptor;

import cn.yh.hospitalappointmentsystemdemo.common.AjaxResult;
import cn.yh.hospitalappointmentsystemdemo.utils.JWTUtils;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if (token == null) {
            System.out.println("token为空，请重新登录！");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.verifyFail("用户认证不通过！")));
            return false;
        }
        String username = JWTUtils.getUsernameByClaim();
//        System.out.println("拦截器已启用      !-----------!         当前用户："+username);
        // 校验token
        // 校验通过，放行
        try {
            JWT.require(Algorithm.HMAC256(JWTUtils.TOKEN_SECRET)).build().verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.verifyFail("用户认证过期！"+username)));
            return false;
        }

        return true;


    }
}
